package lium.lbs.lbsim.activity

import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.buz.hjcdriver.bean.AResultBean
import com.buz.hjcdriver.bean.AllCityResultBean
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.lmlibrary.bean.ResponseBean
import com.lmlibrary.bean.ResponseHelloBean
import kotlinx.android.synthetic.main.acitivty_choosecity.*
import lium.lbs.lbsim.R
import lium.lbs.lbsim.adapter.ChooseCityAdapter
import lium.lbs.lbsim.utils.CharacterParser
import lium.lbs.lbsim.utils.callbck.DialogCallback
import com.lzy.okgo.model.Response
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.StringCallback
import lium.lbs.lbsim.bean.GetCityNewBean
import lium.lbs.lbsim.jgchat.utils.photovideo.takevideo.utils.LogUtils
import lium.lbs.lbsim.utils.ToastUtils
import okhttp3.*
import java.io.IOException


class ChooseCityActivity : BaseActivity(), BaseQuickAdapter.OnItemClickListener {

    var isInitLocationButton = false
    var province: String? = null
    var city: String? = null
    var relter: String? = null

    override fun getLayoutId(): Int {
        return R.layout.acitivty_choosecity
    }

    lateinit var adapter: ChooseCityAdapter
    private val listData: ArrayList<AllCityResultBean> = arrayListOf()


    /**
     * 汉字转换成拼音的类
     */
    private var characterParser: CharacterParser? = null

    override fun initView(savedInstanceState: Bundle?) {
        setTitleWithBack("地址")
        addOnClickListeners(R.id.myaddress)
        initmyview()
        getLocation()
    }

    @SuppressLint("MissingPermission")
    fun getLocation() {
        val locationProvider: String
        //获取地理位置管理器
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        //获取所有可用的位置提供器
        val providers = locationManager.getProviders(true)
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER
        } else {
            Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show()
            return
        }
        //获取Location
        val location = locationManager.getLastKnownLocation(locationProvider)
        if (location != null) {
            //不为空,显示地理位置经纬度
            showLocation(location)
        }
        //监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 3000, 1f, locationListener)
    }

    /**
     * 显示地理位置经度和纬度信息
     *
     * @param location
     */
    private fun showLocation(location: Location) {
        val locationStr = ("纬度：" + location.latitude + "\n" + "经度：" + location.longitude)
        getCity(location.latitude.toString(), location.longitude.toString())
        LogUtils.e("body--locationStr--" + locationStr)
        val syncTask = object : Thread() {
            override fun run() {
                var client = OkHttpClient()
                @Throws(IOException::class)
                fun run(url: String): String {
                    val request = Request.Builder()
                        .url("http://api.map.baidu.com/geocoder?output=json&location=" + location.latitude + "," + location.longitude + "&ak=esNPFDwwsXWtsQfw4NMNmur1" + "&key=")
                        .build()
                    val response = client.newCall(request).execute()
                    return if (response.isSuccessful) {
                        LogUtils.e("body" + response.toString())
                        response.body()!!.string()
                    } else {
                        throw IOException("Unexpected code $response")
                    }
                }

                /*           relter   = HttpUtils(location.latitude.toString(), location.longitude.toString()).toString()
                           LogUtils.e("body--"+relter)
                           val gson = Gson()
                           val bean = gson.fromJson(relter.toString(), GetCityNewBean::class.java)
                           if (bean.status.equals("OK")) {
                               myaddress.text = bean.result.addressComponent.province + bean.result.addressComponent.city
                               province = bean.result.addressComponent.province
                               city = bean.result.addressComponent.city
                           } else {
                               ToastUtils.showToast("定位失败")
                           }*/
            }
        }

        syncTask.start()
    }

    /**
     * LocationListern监听器
     * 参数：地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
     */

    internal var locationListener: LocationListener = object : LocationListener {

        override fun onStatusChanged(provider: String, status: Int, arg2: Bundle) {

        }

        override fun onProviderEnabled(provider: String) {

        }

        override fun onProviderDisabled(provider: String) {

        }

        override fun onLocationChanged(location: Location) {
            //如果位置发生变化,重新显示
            showLocation(location)
        }
    }

    override fun getNetWorkData() {
    }


    private fun initmyview() {
        characterParser = CharacterParser.getInstance()
        adapter = ChooseCityAdapter()
        recyclerView.adapter = adapter
        adapter.disableLoadMoreIfNotFullPage(recyclerView) //关闭BRAVE的自动加载功能 改成 refreshLayout的上拉加载
        adapter.onItemClickListener = this
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        recyclerView.addItemDecoration(
            com.readystatesoftware.chuck.internal.support.DividerItemDecoration(
                this,
                layoutManager.orientation,
                false
            )
        ) //分割线
        mSidBar.setTextView(slide_dialog)
        mSidBar.setOnTouchingLetterChangedListener {
            //该字母首次出现的位置
            var position = 0
            for ((index, cityBean) in adapter.data.withIndex()) {
                if (TextUtils.equals(cityBean.letters, it.toUpperCase())) { //转为大写后 判断是否相同
                    position = index
                    if ("#" == it) {
                        position = -1 //不处理#
                    }
                    if ("A" == it) {
                        position = 1 //不处理#
                    }

                    break
                }
            }
            if (position != -1 && position != 0) {
                recyclerView.scrollToPosition(position)
                var mLayoutManager = recyclerView.layoutManager as LinearLayoutManager
                mLayoutManager.scrollToPositionWithOffset(position, 0)
            }
        }
        getAllCityList()
    }

    private fun getAllCityList() {
        val param = HashMap<String, String>()
        postData("/common/getAllCity", param, object : DialogCallback<ResponseBean<List<AllCityResultBean>>>(this) {
            override fun onSuccess(response: Response<ResponseBean<List<AllCityResultBean>>>) {
                setData(response.body().data)
            }
        })
    }

    private fun setData(list: List<AllCityResultBean>?) {
        listData.clear()
        list?.let {
            for (cityBean in list) {
                val pinyin = characterParser!!.getSelling(cityBean.name)
                val sortString = pinyin.substring(0, 1).toUpperCase()
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]".toRegex())) {
                    cityBean.letters = sortString.toUpperCase()
                } else {
                    cityBean.letters = "#"
                }
                listData.add(cityBean)
            }
        }
        listData.sortBy { it.letters }
        adapter.data.clear()
        adapter.data.addAll(listData)
        adapter.notifyDataSetChanged()

    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        listData[position].name
        saveUserinfo(listData[position].parentName, listData[position].name)
    }


    private fun saveUserinfo(parentName: String, name: String) {
        val param = HashMap<String, String>()
        param["province"] = parentName
        param["city"] = name
        postData("/member/updMemberInfo", param, object : DialogCallback<ResponseBean<AResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<AResultBean>>) {
                ToastUtils.showToast(response.body().msg + "")
                finish()
            }
        })

    }


    private fun getCity(latitude: String, longitude: String) {

        val url =
            "http://api.map.baidu.com/geocoder?output=json&location=" + latitude + "," + longitude + "&ak=esNPFDwwsXWtsQfw4NMNmur1" + "&key="

        OkHttpUtils
            .get()
            .url(url)
            .build()
            .execute(object : StringCallback() {

                override fun onError(call: Call, e: Exception, id: Int) {

                }

                override fun onResponse(response: String, id: Int) {
                    LogUtils.e("body" + response)
                    val gson = Gson()
                    val bean = gson.fromJson(response.toString(), GetCityNewBean::class.java)
                    if (bean.status.equals("OK")) {
                        myaddress.text = bean.result.addressComponent.province + bean.result.addressComponent.city
                        province = bean.result.addressComponent.province
                        city = bean.result.addressComponent.city
                    } else {
                        ToastUtils.showToast("定位失败")
                    }
                }
            })

    }


    override fun onClick(v: View?) {
        super.onClick(v)
        when (v!!.id) {
            R.id.myaddress -> {
                saveUserinfo(this!!.province.toString(), this!!.city.toString())
                finish()
            }
        }
    }

    /**
     * Created by Administrator on 2016-03-27.
     */
    public class HttpUtils(latitude: String, longitude: String) {

        internal var client = okhttp3.OkHttpClient()

        val JSON = MediaType.parse("application/json; charset=utf-8")

        @Throws(IOException::class)
        fun login(url: String, json: String): String {
            //把请求的内容字符串转换为json
            val body = RequestBody.create(JSON, json)
            //RequestBody formBody = new FormEncodingBuilder()

            val request = okhttp3.Request.Builder()
                .url(url)
                .post(body)
                .build()

            val response = client.newCall(request).execute()


            return response.body()!!.string()


        }

        /**
         * 异步:同时执行多个
         * 通过get请求获取数据
         *
         */
        private fun getAsyncOkHttp(latitude: String, longitude: String) {
            val okHttpClient = okhttp3.OkHttpClient()
            val request = okhttp3.Request.Builder().get().url(
                "http://api.map.baidu.com/geocoder?output=json&location=" + latitude + "," + longitude + "&ak=esNPFDwwsXWtsQfw4NMNmur1" + "&key="
            ).build()
            //异步:
            okHttpClient.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {

                }

                @Throws(IOException::class)
                override fun onResponse(call: Call, response: okhttp3.Response) {

                }


            })
        }


    }
}